//
//  CYDiscoveryVC.m
//  CreditAddressBook
//
//  Created by LE on 15/12/15.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYDiscoveryVC.h"
#import "CYButtonView.h"
#import "LEAlertView+LE.h"
#import "CYJumpsTool.h"
#import "CYLoginHttpTool.h"
#import "CYCompanyUserTool.h"
#import "CYUserCarVC.h"
#import "CYMyDefaultRecordsVController.h"
#import "LEMDLib.h"
#import "CYQueryandPayVC.h"
#import "CYMeHttpTool.h"
#import "CYPayViewController.h"
#import "CreditWebViewController.h"
#import "CYCreditBankVC.h"
#import "TOWebViewController.h"
#import "CYPersonReleaseVC.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "UIAlertView+Block.h"
#import "CYCarUnionVC.h"
#import "LEUUID.h"
#import "DSNavigationBar.h"
#import "CYABTool.h"
#import "RHAddressBook.h"
#import "CYMeTool.h"
#import <ZMCreditSDK/ALCreditService.h>
#import "CYUserCarFindWebVC.h"
#import "CXCarouselView.h"
#import "CYLTVC.h"
#import "CYDXVC.h"
#import "CYDXWebVC.h"
#import "CYCreditBaoWebVC.h"
#import "MBProgressHUD+LE.h"
#import "GCD.h"
#import "CYNormalSubmitVC.h"
#import "CYUrltestVC.h"
#import "CYDXWebVC.h"
#import "SDCycleScrollView.h"
#import "DCPaymentView.h"
#import "CYDES3Util.h"
#import "CYAddCreditVC.h"
#import "CYDES3Util.h"
#import "CYZijinrongWebView.h"
#import "CYNewHeightVC.h"


@interface CYDiscoveryVC ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate,UIWebViewDelegate,SDCycleScrollViewDelegate>

@property(nonatomic, strong) GCDTimer *GCDTimer;
@property(nonatomic, weak) UITableView *tableview;
@property (weak, nonatomic) IBOutlet SDCycleScrollView *bannerView;

@property (weak, nonatomic) IBOutlet UIView *backgroundView;
@property (nonatomic, strong)NSString *tag;

@property (nonatomic, strong)NSString *statuesstr;
@property (nonatomic, strong)NSString *signstr;
@property (nonatomic, strong)NSString *pramstr;
@property (nonatomic, strong)NSString *submitparams;

@property (nonatomic, strong)NSArray *picArr;
@property (nonatomic, strong)NSMutableArray *imageArr;
@property (nonatomic, strong)NSMutableArray *webAddress;


@property (nonatomic,strong)UIView *weixinbg;
@property (nonatomic, strong) UIView *weixinView;
@property (nonatomic, strong) UIButton *yzmBtn;

@property (nonatomic, strong) UITextField *accountTF;
@property (nonatomic, strong) UITextField *yzmTF;

@property (nonatomic, strong)UIWebView *webview;
@property (weak, nonatomic) IBOutlet UIView *storezhegaiView;

@end

@implementation CYDiscoveryVC

-(void)viewWillAppear:(BOOL)animated{
     
     //store版本备用 信用查询是否需要
//     [CYHttpTool postWithURL:[CYURL shared].getCredit params:@{} success:^(id json) {
//          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
//          NSString *str = jsoninfo.message;
//          if (str.intValue == 1) {
//               //不展示banner
//                
//          }else{
//               //恢复正常，展示
//               CYLog(@"show");
               _storezhegaiView.hidden = YES;
//          }
//          
//     } failure:^(NSError *error) {
//          CYLog(@"error = %@",error);
//     }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
     
     _imageArr = [[NSMutableArray alloc]init];
     _webAddress = [[NSMutableArray alloc]init];
     [self setupTable];
     [self loadad];
     //预加载
     [self loadhtml];
     [self loadpercent];
     
}

-(void)loadhtml{
     _webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen ]bounds].size.width,[[UIScreen mainScreen ]bounds].size.height)];
     _webview.delegate = self;
     NSString *loadurl = @"http://139.129.220.229:8058/default.html";
     NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:loadurl]];
     [_webview loadRequest:request];
}

-(void)loadpercent{
     CYUser *user = [CYLoginHttpTool userData].user;
     [CYHttpTool postWithURL:[CYURL shared].iosImageCompress params:@{} success:^(id json) {
          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
          NSNumber *a = jsoninfo.data;
          user.percent = a;
          CYLog(@"a = %@",a);
          [CYLoginHttpTool updateUserData:user];
          
     } failure:^(NSError *error) {
          
     }];
}

-(void)loadad{
  @try {
     [CYHttpTool postWithURL:[CYURL shared].getAd params:@{} success:^(id json) {
               CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
               if (jsoninfo.isSuccess) {
                    NSArray *jsonArr = jsoninfo.data;
                    for (NSDictionary *dic in jsonArr) {
                         NSString *str = [dic objectForKey:@"picAddress"];
                         if (str) {
                              [_imageArr addObject:str];
                         }
                         
                         NSString *urlstr = [dic objectForKey:@"webAddress"];
                         if (urlstr) {
                              [_webAddress addObject:urlstr];
                         }
                         
                    }
                    if (_imageArr.count&&_webAddress.count) {
                         [self loaddiscoypicView];
                    }
               }
               
          } failure:^(NSError *error) {
               
          }];
         }
         @catch (NSException *exception) {
              [self reportException:exception];
              //        [[CrashReporter sharedInstance] reportException:exception reason:@"AppDelegate初始化错误" extraInfo:nil];
              CYLog(@"banner错误 %@", exception);
       }
}

- (void)loaddiscoypicView{
     
     if (_webAddress.count && _imageArr) {
          self.bannerView.imageURLStringsGroup = _imageArr;
          _bannerView.autoScrollTimeInterval = 5;
          self.bannerView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
          self.bannerView.delegate = self;
          self.bannerView.currentPageDotColor = [UIColor yellowColor]; // 自定义分页控件小圆标颜色
          self.bannerView.placeholderImage = [UIImage imageNamed:@"placeholder"];
          
     }
     
}
#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
     
     NSLog(@"---点击了第%ld张图片", (long)index);
     if (_imageArr.count) {
          CreditWebViewController *bannerVC = [[CreditWebViewController alloc] initWithUrl:_webAddress[index]];
          bannerVC.hidesBottomBarWhenPushed = YES;
          [self.navigationController pushViewController:bannerVC animated:YES];
     }
     
}


- (void)setupTable {
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,  [UIScreen mainScreen].bounds.size.width+5, 312) style:UITableViewStyleGrouped];
    [self.backgroundView addSubview:table];
    table.dataSource = self;
    table.delegate = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    table.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableview = table;
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if (section == 3){
//        return 2;
//    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
     
     if (indexPath.section == 0){
          UIImage *icon = [UIImage imageWithName:@"自金融-1"];
          CGSize itemSize = CGSizeMake(self.view.width, 90);
          UIGraphicsBeginImageContextWithOptions(itemSize, NO,0.0);
          CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
          [icon drawInRect:imageRect];
          cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
          cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
          
     }
    if (indexPath.section == 1){
        UIImage *icon = [UIImage imageWithName:@"2"];
        CGSize itemSize = CGSizeMake(self.view.width, 90);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO,0.0);
        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }
    if (indexPath.section == 2) {//ic_car_rental
        UIImage *icon = [UIImage imageWithName:@"3"];
        CGSize itemSize = CGSizeMake(self.view.width, 90);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO,0.0);
        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.detailTextLabel.textColor = CYColor(100, 200, 100, 1);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 200;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 104;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     
     if (indexPath.section == 0) {
          CYUser *user = [CYLoginHttpTool userData].user;
          
          if (user) {
          //  自金融
//               if (user.certificateExamineStatus.intValue != 2) {
//                    CYAlertView(@"请先通过实名认证！");
//                    return;
//               }
               CYZijinrongWebView *zjr = [[CYZijinrongWebView alloc]init];
               zjr.hidesBottomBarWhenPushed = YES;
               [[self navigationController]setNavigationBarHidden:YES animated:YES];
               [self.navigationController pushViewController:zjr animated:YES];
               
          }
          else {
               [CYJumpsTool jumpToLogin:self];
          }

          
     }
       if (indexPath.section == 1) {
               //信用银行
           NSString *str = [LEUUID UUIDForVendor];
//           if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
           RHAddressBook *ab = [CYABTool addressBook];
           NSArray *allpeople = ab.people;
           NSArray *contactsArr = [CYMeTool contactsArr];
            CYUser *user = [CYLoginHttpTool userData].user;
            [CYHttpTool postWithURL:[CYURL shared].iosImageCompress params:@{} success:^(id json) {
                 CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
                 
                 NSNumber *a = jsoninfo.data;
                 user.percent = a;
                 CYLog(@"a = %@",a);
                 [CYLoginHttpTool updateUserData:user];
                 
            } failure:^(NSError *error) {
                 
            }];

           if (contactsArr.count) {
               //去除字典中的headerImage
               NSMutableArray *newContactsArr = [NSMutableArray array];
               for (NSDictionary *dic in contactsArr) {
                   if (dic[@"headerImage"]) {
                       NSMutableDictionary *dicMu = [NSMutableDictionary dictionaryWithDictionary:dic];
                       [dicMu removeObjectForKey:@"headerImage"];
                       
                       [newContactsArr addObject:dicMu];
                   } else {
                       [newContactsArr addObject:dic];
                   }
               }
          }

           if (allpeople.count) {
               NSInteger score  = allpeople.count;
               CGFloat val = ((arc4random()%100)/100.f) + 1.f;
               int a = val*score;
               if (score<100) {
                   [CYHttpTool postWithURL:[CYURL shared].saveCreditMachine params:@{@"machineCode":str,@"score":@(a)} success:^(id json) {
                       CYLog(@"json = %@",json);
                       //
                   } failure:^(NSError *error) {
                       CYLog(@"error = %@",error);
                       //
                   }];
               }
           }
                CYCreditBankVC *bvc = [[CYCreditBankVC alloc]init];
                bvc.hidesBottomBarWhenPushed = YES;
                [[self navigationController] setNavigationBarHidden:YES animated:YES];
                [self.navigationController pushViewController:bvc animated:YES];

       }else if(indexPath.section ==2){
            CYUser *user = [CYLoginHttpTool userData].user;
            if (user) {
                 if (user.certificateExamineStatus.intValue != 2) {
                      CYAlertView(@"请先通过实名认证！");
                      return;
                 }
                 [CYHttpTool postWithURL:[CYURL shared].getVip params:nil success:^(id json) {
                      CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
                      CYLog(@"jsoninfo = %@",jsoninfo);
                      NSDictionary *vipdic = jsoninfo.data;
                      if (vipdic) {
                           NSString *vipstr = [vipdic objectForKey:@"vip"];
                           if (vipstr && vipstr.intValue == 1) {
                                //                    //开
                                CYCreditBaoWebVC *cbvc = [[CYCreditBaoWebVC alloc]init];
                                cbvc.hidesBottomBarWhenPushed = YES;
                                [[self navigationController] setNavigationBarHidden:YES animated:YES];
                                [self.navigationController pushViewController:cbvc animated:YES];
                                
                           }else{
                                CYAlertView(@"该功能即将开放，敬请期待");
                           }
                           
                      }
                      
                 } failure:^(NSError *error) {
                      CYLog(@"erro = %@",error);
                 }];
            }else{
                 [CYJumpsTool jumpToLogin:self];
                 
            }
     }
}

//信用通缉
- (IBAction)chazhanghuankuanclick:(id)sender {
     
     //高级认证测试
     //     CYNewHeightVC *height = [[CYNewHeightVC alloc]init];
     //     [self.navigationController pushViewController:height animated:YES];
     
     
     
     CYUser *user = [CYLoginHttpTool userData].user;
     if (user) {
          CYPersonReleaseVC *per = [[CYPersonReleaseVC alloc]init];
          per.hidesBottomBarWhenPushed = YES;
          [self.navigationController pushViewController:per animated:YES];
          
     } else {
          [CYJumpsTool jumpToLogin:self];
     }

     
     
    }

//查账还款
- (IBAction)newchazhangClick:(id)sender {
     
     
     
     CYUser *user = [CYLoginHttpTool userData].user;
     
     if (user) {
          CYPayViewController *pay = [[CYPayViewController alloc] init];
          pay.hidesBottomBarWhenPushed = YES;
          [[self navigationController] setNavigationBarHidden:YES animated:YES];
          [self.navigationController pushViewController:pay animated:YES];
     
     }
     else {
          [CYJumpsTool jumpToLogin:self];
     }
     
//     CYDXVC *dxvc = [[CYDXVC alloc]init];
//     [self.navigationController pushViewController:dxvc animated:YES];
     
     //字符串分解测试
     //// redURL = http://www.189.cn/login/ecs.do?PlatNO=90000&ResultCode=0&Ticket=900002409554f30b94e4982e434fb3ef2aaf00e9d02b&TxID=9000051214c323f8f4833a6d7b42d67f484aa
//     NSString *longstr = @"redURL = http://www.189.cn/login/ecs.do?PlatNO=90000&ResultCode=0&Ticket=900002409554f30b94e4982e434fb3ef2aaf00e9d02b&TxID=9000051214c323f8f4833a6d7b42d67f484aa";
     
     

}


//失信联系人
- (IBAction)xinyongotngjiclicj:(id)sender {
     
  
     
     
     
     CYMyDefaultRecordsVController *myDefault = [CYMyDefaultRecordsVController le_loadFromStoryBoard:self.storyboard];
     myDefault.hidesBottomBarWhenPushed = YES;
     [self.navigationController pushViewController:myDefault animated:YES];
     
//     [CYHttpTool postWithURL:[CYURL shared].getDuobao params:nil success:^(id json) {
//          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
//          if (jsoninfo.isSuccess) {
//               NSDictionary *vipdic = jsoninfo.data;
//               NSString *vipstr = [vipdic objectForKey:@"duobao"];
//               NSString *vipurl = [vipdic objectForKey:@"duobaoUrl"];
//               if (vipstr && vipstr.intValue == 1) {
//                    //开
//                         if (vipurl) {
//                              CreditWebViewController *yiyuanwebVC = [[CreditWebViewController alloc] initWithUrl:vipurl];
//                              yiyuanwebVC.hidesBottomBarWhenPushed = YES;
//                              [self.navigationController pushViewController:yiyuanwebVC animated:YES];
//                              
//                              
//                         }else{
//                              CYAlertView(@"网络错误");
//                         }
//                    
//               }else{
//                    CYAlertView(@"该功能即将开放，敬请期待");
//               }
//          }
//          
//     } failure:^(NSError *error) {
//          CYLog(@"erro = %@",error);
//     }];
   
}

-(void)Bigtext:(NSString *)bigtext Smalltext:(NSString *)smalltext{
     
     CYLog(@"被执行");
}


//积分商城
- (IBAction)shixinlianxirenclick:(id)sender {
     
     CYUser *user = [CYLoginHttpTool userData].user;
     if (user) {
          [CYMeHttpTool ShopwithaddressWithParams:@{@"userId": user.userId} success:^(NSString *message) {
               
               //message
               if (message) {
                    CreditWebViewController *shopwebVC = [[CreditWebViewController alloc] initWithUrl:message];
                    shopwebVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:shopwebVC animated:YES];
                    
               }
               
          } failure:^(NSError *error) {
          }];
          
     }else{
          [CYJumpsTool jumpToLogin:self];
     }

     
     
     //数组区分法
//     NSArray* array = @[@{@"a":@[@"1",@"2"]},@{@"b":@[@"3"]},@{@"c":@[@"5",@"6"]}];
//     NSArray* array2 = @[@{@"f":@[@"1",@"2"]},@{@"d":@[@"4",@"10"]},@{@"c":@[@"5",@"6"]}];
//     NSPredicate* thePredicate = [NSPredicate predicateWithFormat:@"NOT(SELF in %@)",array];
//     NSArray* arr3 = [array2 filteredArrayUsingPredicate:thePredicate];
//     NSLog(@"%@",arr3);
     
     //数组匹配法
//     NSArray *phonearr = @[@"1",@"2",@"3"];
//     NSArray *arr = @[@{@"name1":@[@"1",@"13354909087"]},@{@"name2":@[@"2",@"13354909117"]}];
//     NSMutableArray *findArr = [[NSMutableArray alloc]init];
//     for ( int i = 0; i<phonearr.count; i++) {
//          for (NSDictionary *dic in arr) {
//               NSArray *phones = dic.allValues.firstObject;
//               NSUInteger index = [phones indexOfObject:phonearr[i]];
//               if (index < phones.count) {
//                    [findArr addObject:dic];
//                    break;
//               }
//          }
//     }
//     NSLog(@"findArr = %@",findArr);
   
     
//     NSMutableArray *dataArray1 = [[NSMutableArray alloc]init];
//     NSMutableArray *dataArray2 = [[NSMutableArray alloc]init];
//     NSMutableSet *mixdata = [[NSMutableSet alloc]init];
//     NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//     NSArray *contactsArr = [CYMeTool contactsArr];
//     if (contactsArr.count) {
//          //去除字典中的headerImage
//          NSMutableArray *newContactsArr = [NSMutableArray array];
//          for (NSDictionary *dic in contactsArr) {
//               if (dic[@"headerImage"]) {
//                    NSMutableDictionary *dicMu = [NSMutableDictionary dictionaryWithDictionary:dic];
//                    [dicMu removeObjectForKey:@"headerImage"];
//                    
//                    [newContactsArr addObject:dicMu];
//               } else {
//                    [newContactsArr addObject:dic];
//               }
//          }
//          for (NSMutableDictionary *dic in newContactsArr) {
//               NSString *namestr = [dic objectForKey:@"name"];
//               NSArray *phonestr = [dic objectForKey:@"phone"];
//               [dataArray2 addObject:namestr];
//               [dataArray1 addObject:phonestr];
//          }
//          
//          CYLog(@"dataArray2 = %@",dataArray2);
//          CYLog(@"dataArray1 = %@",dataArray1);
//          for (int i = 0; i<dataArray1.count; i++) {
//               [dic setObject:dataArray1[i] forKey:dataArray2[i]];
//          }
//          CYLog(@"dic= %@",dic);
//          for (int i = 0 ; i<dic.count; i++) {
//               [mixdata addObject:dic];
//          }
//          
//          NSMutableSet *duibidata = [[NSMutableSet alloc]initWithObjects:@{@"Anna Haro":@[@"5555228243"],@"Ceshi":@[@"13354985521"]}, nil];
//          [duibidata minusSet:mixdata];
//          CYLog(@"不一样的数据：%@",duibidata);
//     }

     
     
}
//信用通缉
- (IBAction)bieyawocheClick:(id)sender {
     
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .1f;

}

#pragma mark - 重写
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYNaviThemeColor];
}

@end
